<?php

namespace app\videos\server;

use app\common\server\Service;
use app\videos\model\Report as ReportModel;

class Report extends Service
{

    public function initialize()
    {
        parent::initialize();
        if (!isset($this->serviceKey) || empty($this->serviceKey) || cache('serviceKey') != $this->serviceKey) {
            exit(json_encode(['msg'=>'非法操作！','code'=>712]));
        }
        $this->ReportModel = new ReportModel();
    }
    /**
     * @param {Object} $data 记录错误视频
     */
    public function report($data, $user) {
        $map = [];
        $map[] = ['vod_id', 'eq', $data['vod_id']];
        $map[] = ['vod_index', 'eq', $data['vod_index']];
        if ($model = $this->ReportModel->where($map)->find()) {
            // 如果处理状态是1，重置状态及反馈次数
            if ($model->status == 1) {
                // 一个用户一个视频当前索引一天只能提交一次
                cache($user['id'] . md5(json_encode($data)), 1, 86400);
                $model->number = 1;
                $model->status = 0;
                return $model->save();
            }
            // 如果状态不是1，用户有没有反馈过
            if (cache($user['id'] . md5(json_encode($data)))) {
                $this->error = '反馈已提交，我们将尽快处理';
                return false;
            } else {
                cache($user['id'] . md5(json_encode($data)), 1, 86400);
                $model->number = $model->number + 1;
                return $model->save();
            }
        }
        // 一个用户一个视频当前索引一天只能提交一次
        cache($user['id'] . md5(json_encode($data)), 1, 86400);
        return $this->ReportModel->allowField(true)->save($data);
    }
    
}
